// 微信支付回调
import { NextResponse } from 'next/server'
import { verifyWeChatCallbackSign,queryOrderByOutTradeNo } from '@/pay/payService';
import { updateOrderPaymentByOutTradeNo } from '@/lib/courtBookingService';

export async function POST(request) {

  console.log("we have received a wechat pay callback", request);
  try {
    // 获取 headers 对象
  const headers = request.headers;
  const timestamp = headers.get("wechatpay-timestamp");
  const nonce = headers.get("wechatpay-nonce");
  const signature = headers.get("wechatpay-signature");
  const serial = headers.get("wechatpay-serial");

  const body = await request.json();

  console.log('we have received a wechat pay callback',{timestamp,nonce,signature,serial,body})

  const { isValid, wepayOrder } = verifyWeChatCallbackSign({
      timestamp,
      nonce,
      signature,
      serial,
      body
    });
    if (!isValid) {
      return NextResponse.json({ message: "invalid signature" }, { status: 401 });
    }
    console.log("we have verified the wechat pay callback", wepayOrder);
    if (wepayOrder.trade_state == "SUCCESS") {
      const orderNo = wepayOrder.out_trade_no;
      const openId = wepayOrder.payer.openid;
      console.log("orderNo", orderNo);
      console.log("openId", openId);
      //从微信服务器查询订单
      const order = await queryOrderByOutTradeNo(orderNo);
      if (order.trade_state == "SUCCESS") {
        /**
         *  * 【交易状态】 交易状态，枚举值：
         * SUCCESS：支付成功
         * REFUND：转入退款
         * NOTPAY：未支付
         * CLOSED：已关闭
         * REVOKED：已撤销（仅付款码支付会返回）
         * USERPAYING：用户支付中（仅付款码支付会返回）
         * PAYERROR：支付失败（仅付款码支付会返回）
         */
        // 更新订单状态
        await updateOrderPaymentByOutTradeNo(orderNo, {
          "is_paid": true,
          "status": "active",
          "memo": "支付已完成"
        })
      }
    }
    return NextResponse.json({ message: "handle the wechat pay callback successfully" }, { status: 200 });
  } catch (error) {
    console.error("handle the wechat pay callback failed", error);
    return NextResponse.json({ message: "handle the wechat pay callback failed", error: error.message }, { status: 500 });
  }
}


//write get test

export async function GET(request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')
  const state = searchParams.get('state')
  console.log(code, state)
  return NextResponse.json({ message: 'success' })
}
